<script setup>
import { ref } from 'vue'
import { ElInput, ElButton } from 'element-plus'

const sid = ref('')
const toid = ref('')
const message = ref('')
const receivedMessages = ref([])
const socket = ref(null)

const connectWebSocket = () => {
  if (sid.value) {
    socket.value = new WebSocket(`ws://localhost:3014/websocket/${sid.value}`)

    socket.value.onmessage = (event) => {
      receivedMessages.value.push(event.data)
    }

    socket.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
    }
  }
}

const sendMessage = () => {
  if (socket.value?.readyState === WebSocket.OPEN) {
    socket.value.send(JSON.stringify({
      sid: toid.value,
      message: message.value
    }))
    message.value = ''
  }
}
</script>

<template>
  <div class="form-container">
    <el-input
      v-model="sid"
      placeholder="输入用户ID"
      style="width: 300px; margin: 10px"
    />
    <el-button
      type="success"
      @click="connectWebSocket"
      style="margin: 10px"
    >
      建立连接
    </el-button>

    <el-input
      v-model="toid"
      placeholder="接收方ID"
      style="width: 300px; margin: 10px"
    />
    <el-input
      v-model="message"
      placeholder="消息内容"
      style="width: 300px; margin: 10px"
    />
    <el-button
      type="primary"
      @click="sendMessage"
      style="margin: 10px"
    >
      发送消息
    </el-button>

    <div class="message-box">
      <h3>收到消息:</h3>
      <pre>{{ receivedMessages }}</pre>
    </div>
  </div>
</template>

<style>
.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
}

.message-box {
  width: 500px;
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
